<template>
  <div>
    <!--新增按钮-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="add">新增</el-button>
      <el-button>其他</el-button>
    </div>
    <!--搜索框-->
    <div style="margin: 10px 0">
      <el-input v-model="keywords" placeholder="请输入关键字" style="width: 30%"></el-input>
      <el-button style="margin-left: 10px" type="primary" @click="search">查询</el-button>
    </div>
    <el-table :data="tableData" style="width: 90%">
      <el-table-column prop="name" label="家居名"/>
      <el-table-column prop="maker" label="厂商"/>
      <el-table-column prop="price" label="价格"/>
      <el-table-column prop="sales" label="销量"/>
      <el-table-column prop="stock" label="库存"/>
      <el-table-column fixed="right" label="操作">
    <!--自定义内容需要使用该行数据时，需要声明#default="scope" 再通过scope.row获取数据，即插槽机制-->
        <template #default="scope">
          <el-button type="primary" v-on:click="handleClick(scope.row)">编辑</el-button>
          <!--引入气泡确认框组件-->
          <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              v-on:confirm="handleDelete(scope.row.id)"
              title="确认删除？">
            <template #reference>
              <el-button type="danger" >删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <!--引入分页组件-->
      <el-pagination
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10]"
          :page-size="pageSize"
          layout="total,sizes,perv,pager,next,jumper"
          :total="total"
          background>

      </el-pagination>
    </div>
    <el-dialog v-model="dialogVisible" title="新增家居" width="30%" >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <!--prop表示和rules的哪个规则关联/绑定-->
        <el-form-item label="家居名" prop="name">
          <el-input v-model="form.name" style="width: 50%" />
          <el-text class="mx-1">{{serverError.name}}</el-text>
        </el-form-item>
        <el-form-item label="厂商" prop="maker">
          <el-input v-model="form.maker" style="width: 50%" />
          <el-text class="mx-1">{{serverError.maker}}</el-text>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="form.price" style="width: 50%" />
          <el-text class="mx-1">{{serverError.price}}</el-text>
        </el-form-item>
        <el-form-item label="销量" prop="sales">
          <el-input v-model="form.sales" style="width: 50%" />
          <el-text class="mx-1">{{serverError.sales}}</el-text>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" style="width: 50%" />
          <el-text class="mx-1">{{serverError.stock}}</el-text>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
          </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// @ is an alias to /src
// import HelloWorld from '@/components/HelloWorld.vue'
//引入axios对象，用于发送ajax请求
import request from "@/utils/request";
import { ElMessage } from 'element-plus'

export default {
  name: 'HomeView',
  data(){ //数据池，由于组件需要导出，所以数据池数据采用方法返回，保证每次导出数据是单一的不受影响
    return {
      currentPage: 1, // 当前页
      pageSize: 5, // 每页显示多少条数据
      total: 10,  //共有多少条记录，通过请求获取记录数
      keywords: "",
      dialogVisible: false, //控制对话框是否显示，默认为false不显示
      tableData:[

      ],
      form: {

      },
      rules: {  //提交表单的验证规则
        name: [
          {required: true, message: '请输入家具名称', trigger: 'blur'}
        ],
        maker: [
          {required: true, message: '请输入制造厂商', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {pattern: /^([1-9]\d*|0)(\.\d+)?$/, message: '请输入数字', trigger: 'blur'}
        ],
        sales:[
          {required: true, message: '请输入销量', trigger: 'blur'},
          {pattern: /^([1-9]\d*|0)$/, message: '请输入整数', trigger: 'blur'}
        ],
        stock:[
          {required: true, message: '请输入库存', trigger: 'blur'},
          {pattern: /^([1-9]\d*|0)$/, message: '请输入整数', trigger: 'blur'}
        ]
      },
      serverError:{ //关联后端校验信息

      }
    }
  },
  components: {
    //HelloWorld
  },
  methods: {  // 方法池
    handlePageSizeChange(pageSize) {  //处理pageSize的变化
      this.pageSize = pageSize;
      //刷新家居列表
      this.search();
    },
    handleCurrentChange(currentPage) {  //处理currentPage的变化
      this.currentPage = currentPage;
      //刷新家居列表
      this.search();
    },
    handleClick(row) {  //点击修改家居
      this.dialogVisible = true;
      //回显家居信息
      //1.先将row对象转换成json字符串
      let jsonStr = JSON.stringify(row);
      //再将json字符串转成json对象
      let jsonObj = JSON.parse(jsonStr);
      this.form = jsonObj;
    },
    handleDelete(id) { //点击删除家居
      request.delete("/api/deleteFurn?id=" + id)
          .then((result) => {
            if (result.code === 200) {
              //弹出删除成功的标识
              ElMessage({
                message: '删除成功',
                type: 'success',
              })
              //刷新家居列表
              this.search();
            } else {
              //弹出更新失败的标识
              ElMessage.error('删除失败')
              //刷新家居列表
              this.search();
            }
          })
    },
    add() {
      //清空上一次填写的表单内容
      this.form = {};
      //显示添加的对话框
      this.dialogVisible = true;
    },
    save() {  //新增/更新家居
      if (this.form.id != null) {  //表示更新
        request.put("/api/updateFurn", this.form)
            .then((result) => {
              if (result.code === 200) {
                //弹出更新成功的标识
                ElMessage({
                  message: '更新成功',
                  type: 'success',
                })
                this.dialogVisible = false;
                //清空数据池form表单数据
                this.form = {};
                //再次刷新列表
                this.search();
              } else {
                //弹出更新失败的标识
                ElMessage.error('更新失败')
                this.dialogVisible = false;
                //清空数据池form表单数据
                this.form = {};
                //再次刷新列表
                this.search();
              }
            })
      } else {  //表示添加
        //添加家居
        // request.post("/api/saveFurn", this.form)
        //     .then((result) => { //result就是后端返回给前端的结果
        //       console.log("result=", result)
        //       this.dialogVisible = false;
        //       this.search();  //调用查询方法，刷新家居列表
        //     })
        //如果表单验证不通过，就不提交
        this.$refs['form'].validate((valid) => {
          //验证后端校验错误信息，放行前端校验
          // valid = true;
          if(valid){  //验证通过
            request.post("/api/saveFurn", this.form)
                .then((result) => { //result就是后端返回给前端的结果
                  if (result.code === 200) {  //添加成功
                    console.log("result=", result)
                    this.dialogVisible = false;
                    this.search();  //调用查询方法，刷新家居列表
                  } else if (result.code === 400) {  //添加失败(后端校验失败)
                    this.serverError.name = result.data.name
                    this.serverError.maker = result.data.maker
                    this.serverError.price = result.data.price
                    this.serverError.sales = result.data.sales
                    this.serverError.stock = result.data.stock
                  }

                })
          } else {
            //弹出验证失败的标识
            ElMessage.error('表单验证未通过，不提交')
            return false;
          }
        })
      }
    },
    search() {//分页查询所有家居信息
      request.get("/api/listFurnByLambda", {
        params:{
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          name: this.keywords
        }
      }).then((result) => {
            console.log("result=", result)
            this.tableData = result.data.records
            //修改对应的total
            this.total = result.data.total
          })
    }
  },
  created() { //生命周期函数created：data和methods中的方法已经初始化结束并可以访问，但是未在页面渲染
    // 在此调用查询方法，可以初始化data中tableData数据
    this.search();
  }
}
</script>
